package com.best.smart.log;

import android.content.Context;
import android.util.Log;

import com.orhanobut.logger.LogAdapter;
import com.orhanobut.logger.LogStrategy;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class FileLoggerAdapter implements LogAdapter {
    private final LogStrategy logStrategy;
    //private final int logLevel;

    public FileLoggerAdapter(Context context) {
        File logFile = new File(context.getFilesDir(), "vlog_"+getCurrentDate()+".log");
        this.logStrategy = new WriteToFileLogStrategy(logFile);
        //this.logLevel = Log.ERROR;
    }

    public static String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始，需要加1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return year + "_" + (month < 10 ? "0" + month : month) + "_" + (day < 10 ? "0" + day : day);
    }

    @Override
    public boolean isLoggable(int priority, String tag) {
        return true;
    }

    @Override
    public void log(int priority, String tag, String message) {
        logStrategy.log(priority, tag, message);
    }

    private static class WriteToFileLogStrategy implements LogStrategy {

        private final File logFile;
        private final SimpleDateFormat dateFormat;

        WriteToFileLogStrategy(File logFile) {
            this.logFile = logFile;
            this.dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
        }

        @Override
        public void log(int priority, String tag, String message) {
            try (FileWriter fileWriter = new FileWriter(logFile, true)) {
                String timestamp = dateFormat.format(new Date());
                String info = String.format("%s : %s", timestamp, message);
                fileWriter.write(info);
                fileWriter.write(System.lineSeparator());
            } catch (IOException e) {
                Log.e("FileLogAdapter", "Error writing log to file", e);
            }
        }
    }
}
